package net.ant.watercalc.web.utils;

import com.xiaoleilu.hutool.io.resource.ResourceUtil;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.ImageTranscoder;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.springframework.util.ResourceUtils;
import sun.misc.BASE64Decoder;

import java.io.*;

public class ImgUtil {

    public static byte[] getImageBytes(String img64) throws IOException {
        String[] arr = img64.split(",");

        String imgStr = arr.length > 1 ? arr[1] : img64;
        BASE64Decoder decoder = new BASE64Decoder();
        return decoder.decodeBuffer(imgStr);
    }

    public static byte[] getImageBySvg(String svgCode) {
        byte[] outByte = new byte[]{};
        ByteArrayOutputStream outArr = new ByteArrayOutputStream();
        try {
            byte[] svgBytes = svgCode.getBytes("UTF-8");
            JPEGTranscoder coder = new JPEGTranscoder();
            TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(svgBytes));

            TranscoderOutput out = new TranscoderOutput(outArr);
            coder.transcode(input, out);

            outByte = outArr.toByteArray();
        } catch (TranscoderException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outArr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return outByte;
    }

}
